﻿using MQTTnet.Diagnostics;
using MQTTnet;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace JESAI.MQTT.Client.Diagnostics
{
    public class MQTTPackageInspection
    {
        public static async Task Inspect_Outgoing_Package()
        {
            /*
             * This sample covers the inspection of outgoing packages from the client.
             */

            var mqttFactory = new MqttFactory();

            using (var mqttClient = mqttFactory.CreateMqttClient())
            {
                var mqttClientOptions = mqttFactory.CreateClientOptionsBuilder()
                    .WithTcpServer("broker.hivemq.com")
                    .Build();

                mqttClient.InspectPacketAsync += OnInspectPacket;

                await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);

                Console.WriteLine("MQTT client is connected.");

                var mqttClientDisconnectOptions = mqttFactory.CreateClientDisconnectOptionsBuilder()
                    .Build();

                await mqttClient.DisconnectAsync(mqttClientDisconnectOptions, CancellationToken.None);
            }
        }

        static Task OnInspectPacket(InspectMqttPacketEventArgs eventArgs)
        {
            if (eventArgs.Direction == MqttPacketFlowDirection.Inbound)
            {
                Console.WriteLine($"IN: {Convert.ToBase64String(eventArgs.Buffer)}");
            }
            else
            {
                Console.WriteLine($"OUT: {Convert.ToBase64String(eventArgs.Buffer)}");
            }

            return Task.CompletedTask;
        }
    }
}
